import { EllipsisOutlined } from '@ant-design/icons';
import { Flex, Input, message, Spin, TableProps, Tabs, TabsProps } from 'antd';
import { debounce } from 'lodash';
import React, { useEffect, useState, useCallback } from 'react';

import appService from '@/api/services/appService';
import datasetService from '@/api/services/datasetService.ts';
import { InitializeData, KnowledgeReq } from '@/common/types';
import { SvgIcon } from '@/components/icon';
import TipsModals from '@/components/modals/TipsModals';
import NotData from '@/components/NotData';
import PagesHeader from '@/components/pages-header';
import Tables from '@/components/tables/tables';

import './index.scss';

import { useParams } from '@/router/hooks';
import { formatData } from '@/utils/time';
import useModal from '@/hooks/use-modal/useModal';

import ViewAllModal from './components/ViewAllModal';
import RejectReasonModal from './components/RejectReasonModal';

import { KnowledgeBaseApprovalStore } from '@/store/knowledgeBaseApproval';
import { useUserInfo } from '@/store/userStore';

import { getKnowledgeStatus, getKnowledgeType } from './utils/knowledge';

import TipDesc from '@/components/tipDesc/tipDesc';

interface TablesProps {
  key: React.Key;
  name: string;
  type: string;
  describe: string;
  founder: string;
  createTime: string;
  callTool: string[];
  test: string;
  checkStatus: string;
  items: any;
  _id: any;
}
interface CollectionData {
  list: Array<{ a?: string; q?: string }>;
}

function AppReview() {
  const {
    setIsButtonShow,
    setRadioValue,
    radioValue,
    fetchCheckoutList,
    setCheckoutList,
    setShowTitle,
    setRepetitionDataList,
  } = KnowledgeBaseApprovalStore();
  const modal = useModal('update', 'personnel', 'delete', 'edit', 'all');
  const [messageApi, contextHolder] = message.useMessage();
  const { appId = '', key = '1' } = useParams() as { appId: string; key: string };
  const { userId, groupId } = useUserInfo() as {
    userId: string;
    groupId: string;
  };
  // 弹窗
  const [isModalOpen, setIsModalOpen] = React.useState(false); // 驳回弹框
  // 所有文档的数据
  const [allDownloadData, setAllDownloadData] = useState([]); // 修改状态
  const [originalData, setOriginalData] = useState([]); // 原始状态
  const [isShow, setIsShow] = useState(false);
  // 默认选择第一个文档内容
  const [allDownloadIndex, setAllDownloadIndex] = useState(0);
  // 审批参数
  const [approvalParam, setApprovalParam] = React.useState<KnowledgeReq>({
    page: 1,
    page_size: 10,
    // group_id: '',
    offset: 0,
    searchText: '',
    app_id: appId,
  });
  // 返回值
  const [approvalData, setApprovalData] = React.useState({
    list: [],
    total: 0,
  });
  const [keys, setKeys] = React.useState(key);
  const [value, setValue] = React.useState('');
  // const [scroll, setScroll] = useState({ x: 'calc(700px + 50%)', y: 'calc(80vh - 100px)' });
  // const tableRef = useRef<HTMLDivElement>(null);
  // const size = useSize(tableRef);
  const [rejectValue, setRejectValue] = useState('');
  const [rejectRow, setRejectRow] = useState({});
  // 收集获取的数据
  const [rowData, setRowData] = useState({});
  const [url, setPreviewUrl] = useState('');
  const [fileName, setFileName] = useState('');
  const [loading, setLoading] = useState(false);
  const [defaultTrigger, setDefaultTrigger] = useState(false); // 默认为通过
  const [defaultValue, setDefaultValue] = useState(''); // 默认为通过
  const [footer, setFooter] = useState(false);
  const [initializeData, setInitializeData] = useState<InitializeData>(null);
  const [isApproval, setIsApproval] = useState(false);
  const [approvalHistory, setApprovalHistory] = useState<any>({});
  const [isLoadingModal, setIsLoadingModal] = useState(true);
  const [isRepeat, setIsRepeat] = useState(false);
  const [isDeleteObj, setIsDeleteObj] = useState({
    ids: [],
    appId: '',
  });

  /**
   * @description: 获取审批数据
   */
  const getKnowledgeBaseApprovalList = async () => {
    try {
      const res = await datasetService.knowledgeBaseApprovalList(approvalParam);
      setApprovalData({
        list: res.list.map((item: any, index: number) => ({
          ...item,
          key: `${item._id}_${index}`,
        })),
        total: res.total,
      });
      setDefaultTrigger(false); // 更改状态
      modal.update.close();
    } catch (error) {
      messageApi.error('获取失败');
    }
  };
  /**
   * @description: 获取审批历史数据
   */
  const getKnowledgeBaseApprovalHistoryList = async () => {
    try {
      const res = await datasetService.knowledgeBaseApprovalListHistory(approvalParam);
      setApprovalData({
        list: res.list.map((item: any, index: number) => ({
          ...item,
          key: `${item._id}_${index}`,
        })),
        total: res.total,
      });
      modal.update.close();
    } catch (error) {
      messageApi.error('获取失败');
    }
  };
  const getInitialize = async () => {
    const res = await appService.initialize();
    setInitializeData(res);
    if (res.is_knowledge_manager && !res.is_knowledge_reviewer) {
      setKeys('2');
    }
  };
  const fetchData = useCallback(
    debounce(async (currentKey: string) => {
      try {
        currentKey === '1'
          ? await getKnowledgeBaseApprovalList()
          : await getKnowledgeBaseApprovalHistoryList();
      } catch (err) {
        console.error('数据获取失败:', err);
      }
    }, 300),
    [],
  );

  // 监听表格大小变化，更新滚动条位置
  // useEffect(() => {
  //   if (tableRef.current && size) {
  //     setScroll({
  //       x: 'calc(700px + 50%)',
  //       y: `${size?.height - 140}px`,
  //     });
  //   }
  // }, [size]);

  useEffect(() => {
    // 获取审批数据
    // getKnowledgeBaseApprovalList();
    // 获取审批历史数据
    // getKnowledgeBaseApprovalHistoryList()
    getInitialize();
    modal.update.open(); // 打开加载中
  }, []);
  useEffect(() => {
    // if (!initializeData) return; // 等待初始化完成
    setApprovalData({ list: [], total: 0 }); // 清空旧数据
    // fetchData(keys);
    if (keys === '1') {
      getKnowledgeBaseApprovalList();
    } else {
      getKnowledgeBaseApprovalHistoryList();
    }
  }, [approvalParam, keys]);
  useEffect(() => {
    if (keys === '1' && footer) {
      changeHandlePassReject(allDownloadData);
    }
  }, [footer]);

  // 处理多个文档的内容
  async function changeAllDownload(items: any) {
    // Promise.all(
    //   items.map((item: any) => {
    const id = items?.fileId || items?.collectionId;
    try {
      if (items.type === 'FAQ' || items.type === 'QA') {
        const res = await datasetService.getCollectionDatas({
          collectionId: id,
        });
        setFileName(extractFAQContent(res));
        setPreviewUrl('');
      } else {
        const res = await datasetService.collectionPreviewInfo({
          collection_id: id,
        });

        if (res.type == 'link') {
          window.open(res.url);
        } else if (res.type == 'file') {
          setLoading(true);
          setFileName(res.filename);
          // setIsPreview(true);
          if (res.filename.endsWith('.md')) {
            setPreviewUrl(res.file_url);
          } else {
            setPreviewUrl(`${res.url}`);
          }
        }
      }
      fetchCheckoutList(items.appId, items.collectionId);
    } catch (error) {
      if (error.code === 500) {
        setPreviewUrl('');
      }
    }

    // }),
    // ).then((res) => {
    //   console.log(res);
    // });
  }

  function extractFAQContent(collectionData: CollectionData): string {
    return collectionData.list
      .map((item) => item.a || '')
      .filter((content) => content.trim() !== '')
      .join('\n\n');
  }

  /**
   * @description: 打开弹窗

  /**
   * @description: 切换Tabs
   * @param {string} key
   * @return {*}
   */
  const onChange = (key: string) => {
    setKeys(key);
    setApprovalParam({
      page: 1,
      page_size: 10,
      offset: 0,
      searchText: '',
      // group_id: '',
      app_id: appId,
    });
    setValue('');

    modal.update.open();
  };

  /**
   * @description: Tabs选项
   * @return {*}
   */
  const items: TabsProps['items'] = [
    {
      key: '1',
      label: <div className="text-sm">待审核知识库</div>,
    },
    {
      key: '2',
      label: <div className="text-sm">审批历史</div>,
    },
  ];

  /**
   * @description: TablesColumns
   * @return {*}
   */
  const columns: TableProps<TablesProps>['columns'] = [
    {
      title: '名称',
      dataIndex: 'username',
      key: 'username',
      width: 150,
      render: (_, record) => <div>{record?._id?.username}</div>,
    },
    {
      title: '学/工号',
      dataIndex: 'identityId',
      key: 'identityId',
      width: 150,
      render: (_, record) => {
        if (record?._id?.identityId != '') {
          return <div>{record?._id?.identityId}</div>;
        }
        return <div>-</div>;
      },
    },
    {
      title: '所属组织',
      dataIndex: 'group_name',
      key: 'group_name',
      width: 150,
      render: (_, record) => <div>{record?._id?.group_name}</div>,
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      width: 120,
      render: (_, record) => <div>{record?._id?.role}</div>,
    },
    {
      title: '应用',
      dataIndex: 'appname',
      width: 150,
      key: 'appname',
      render: (_, record) => <div>{record?._id?.appname}</div>,
    },
    {
      title: '操作类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (_, record) => <div>{getKnowledgeType(record?.items)}</div>,
    },
    {
      title: '涉及文档',
      dataIndex: 'callTool',
      key: 'callTool',
      width: 220,

      render: (_, record) => <div>{getCallTool(record?.items)}</div>,
    },
    {
      title: '剩余审批文件',
      dataIndex: 'items',
      key: 'items',
      width: 130,
      render: (_, record) => <div>{keys === '1' && <div>{record?.items.length}</div>}</div>,
    },
    {
      title: '提交时间',
      dataIndex: 'publishTime',
      key: 'publishTime',
      width: 150,

      render: (_, record) => {
        if (record?._id?.publishTime) {
          // return <div>{formatData(record?._id?.publishTime)}</div>;
          return (
            <div>
              {keys === '1'
                ? formatData(record.items[0].publishTime)
                : formatData(record.items[0].updateTime)}
            </div>
          );
        }
        return <div>-</div>;
      },
    },
    {
      title: <div>{keys === '1' ? '审批' : '审批结果'}</div>,
      width: 180,
      key: 'checkStatus',
      render: (_, record) => (
        <div>
          {keys === '1' ? (
            <div className="flex">
              <a
                className=" flex items-center  !text-@brand-color"
                onClick={() => handlePassed(record.items)}
              >
                <SvgIcon icon="message-ic4" size="15" className="mr-1" />
                通过
              </a>
              <a
                className="ml-6  flex items-center  !text-@error-color"
                onClick={() => handleModalOpen(record)}
              >
                <SvgIcon icon="message-ic5" size="15" className="mr-1" />
                驳回
              </a>
            </div>
          ) : (
            <div>{getCheckStatus(record)}</div>
          )}
        </div>
      ),
    },
    {
      title: '操作',
      width: 200,
      key: 'status',
      render: (_, record) => <div>{getStatus(record)}</div>,
    },
  ];

  function getCallTool(item: any) {
    // 只保留前三条数据
    const displayedItems = (item || []).slice(0, 3);
    return (
      <div>
        {displayedItems.map((dataItem: any, i: number) => (
          <div key={i}>
            <div className="">{dataItem.fileName}</div>

            {/* 只在最后一条显示"查看内容" */}
            {i === displayedItems.length - 1 && (
              <a className="!text-@brand-color" onClick={() => handleModalAllDownloadOpen(item)}>
                <EllipsisOutlined />
                查看内容
              </a>
            )}
          </div>
        ))}
      </div>
    );
  }

  function getCheckStatus(item: any) {
    const arr = item?.items;
    let uploadRejectNum = 0;
    let deleteRejectNum = 0;
    let passNum = 0;
    for (let i = 0; i < arr.length; i++) {
      if (
        arr[i]?.reviewStatus === 'upload_reject' ||
        arr[i]?.reviewStatus === 'upload_reject_review' ||
        arr[i]?.reviewStatus === 'upload_reject_delete'
      ) {
        uploadRejectNum++; // 上传驳回
      }
      if (
        arr[i]?.reviewStatus === 'delete_reject' ||
        arr[i]?.reviewStatus === 'delete_reject_review' ||
        arr[i]?.reviewStatus === 'delete_reject_ignore'
      ) {
        deleteRejectNum++; // 删除驳回
      }
      if (arr[i]?.reviewStatus === 'upload_pass' || arr[i]?.reviewStatus === 'delete_pass') {
        passNum++;
      }
    }
    if (uploadRejectNum === arr.length) {
      return (
        <div>
          <div className="w-[74px] rounded bg-[#FFF1F0] px-2 py-1 text-center text-@error-color ">
            上传驳回
          </div>
          <div>{item?._id?.publishTime ? formatData(item?._id?.publishTime) : '-'}</div>
        </div>
      );
    }
    if (deleteRejectNum === arr.length) {
      return (
        <div>
          <div className="w-[74px] rounded bg-[#FFF1F0] px-2 py-1 text-center text-@error-color ">
            删除驳回
          </div>
          <div>{item?._id?.publishTime ? formatData(item?._id?.publishTime) : '-'}</div>
        </div>
      );
    }
    if (passNum === arr.length) {
      return (
        <div>
          <div className="w-[44px] bg-[#F0F8FF] px-2 py-1  text-@brand-color">通过</div>
          <div>{item?._id?.publishTime ? formatData(item?._id?.publishTime) : '-'}</div>
        </div>
      );
    }
    // if (Anum !== arr.length && Bnum !== arr.length) {
    //   return (
    //     <div>
    //       <div className=" w-[72px] bg-[#FFF4E8] px-2 py-1  text-@warning-color">部分驳回</div>
    //       <div className="mb-2 text-[#B6B6B6]">
    //         {item?._id?.publishTime ? formatData(item?._id?.publishTime) : '-'}
    //       </div>
    //       <div
    //         className="cursor-pointer text-@brand-color"
    //         onClick={() => handleModalAllDownloadOpen(arr)}
    //       >
    //         查看
    //       </div>
    //     </div>
    //   );
    // }
  }

  function getStatus(item: any) {
    const arr = item?.items;
    const status = getKnowledgeStatus(arr); // 处理是否已经选择过的状态
    if (status !== '') {
      return <div className="text-sm text-text-3 ">{status}</div>;
    }
    let uploadRejectNum = 0;
    let deleteRejectNum = 0;
    const uploadIds: any = [];
    const deleteIds: any = [];
    for (let i = 0; i < arr.length; i++) {
      if (arr[i]?.reviewStatus === 'upload_reject' && arr[i]?.groupId === groupId) {
        uploadIds.push(arr[i]._id);
        uploadRejectNum++;
      }
      if (arr[i]?.reviewStatus === 'delete_reject' && arr[i]?.groupId === groupId) {
        deleteIds.push(arr[i]._id);
        deleteRejectNum++;
      }
    }
    // if (arr[0].reviewStatus === 'upload_pending') {
    //   return '-';
    // }
    if ((uploadRejectNum !== 0 || deleteRejectNum !== 0) && item._id?.isReview) {
      return (
        <div className="flex">
          <a
            className="flex items-center !text-@brand-color"
            onClick={() => {
              setIsApproval(true);
              setIsModalOpen(true);
              setIsButtonShow(false);
              setApprovalHistory(
                arr.filter(
                  (item: any) =>
                    item.reviewStatus === 'upload_reject' || item?.reviewStatus === 'delete_reject',
                ),
              );
            }}
          >
            <SvgIcon icon="message-ic6" size="20" className="mr-1" />
            重新审批
          </a>
          {uploadRejectNum !== 0 && (
            <a
              className="ml-4 flex items-center !text-@error-color"
              onClick={async () => {
                // 当上传的文件处于驳回状态时，所执行的删除为彻底删除；
                // if (ids1.length == 0) {
                setIsDeleteObj({
                  ids: uploadIds,
                  appId: arr[0].appId,
                });
                // } else {
                //   setIsDeleteObj({
                //     ids: ids2,
                //     appId: '',
                //   });
                // }
                modal.delete.open();
              }}
            >
              <SvgIcon icon="message-ic3" size="20" className="mr-1" />
              删除文件
            </a>
          )}
          {deleteRejectNum !== 0 && (
            <a
              className="ml-4 flex items-center !text-@error-color"
              onClick={async () => {
                await datasetService.reviewApprovalDocument({
                  ids: deleteIds,
                  operator: 'delete',
                  reason: '',
                  appId: arr[0].appId,
                  groupId: arr[0].groupId,
                  reviewStatus: 'delete_reject_ignore',
                });
                message.success('忽略成功');
                getKnowledgeBaseApprovalHistoryList();
              }}
            >
              <SvgIcon icon="message-ic21" size="20" className="mr-1" />
              忽略
            </a>
          )}
        </div>
      );
    }
    return '-';
  }

  const deleteDocument = async () => {
    try {
      if (isDeleteObj.appId !== '') {
        await datasetService.deleteApprovalDocument(isDeleteObj);
      } else {
        await datasetService.deleteDatasetFile(isDeleteObj);
      }
      getKnowledgeBaseApprovalHistoryList();
    } catch (error) {
      messageApi.error('删除失败');
    }
    modal.delete.close();
  };

  const reApproval = async (row: any) => {
    const ids: any = [];
    try {
      row.forEach((item: any) => {
        ids.push(item._id);
      });

      await datasetService.reviewApprovalDocument({
        ids,
        operator: row[0].reviewStatus === 'upload_reject' ? 'upload' : 'delete',
        reason: rejectValue,
        appId: row[0].appId,
        groupId: row[0].groupId,
        reviewStatus:
          row[0].reviewStatus === 'upload_reject' ? 'upload_reject_review' : 'delete_reject_review',
      });
      messageApi.success('重新审批发布成功');
      getKnowledgeBaseApprovalHistoryList();
      setIsApproval(false); // 用完改成false
      setIsLoadingModal(true);
    } catch (error) {
      // messageApi.error('审核失败');
    }
  };

  /**
   * @description: 审核通过
   *  * @param {Array} row - 包含多个文件的数组
   * @param {Object} rowData - 当前操作的对象
   * @return {*}
   */
  const handlePassed = (row: any) => {
    // 需要知道用户点击的是哪一个  如果是同一个往下走，不一样的话，则进入通过
    const isRowDataInList = row.some(
      (item: any) => item.fileId || item.collectionId === rowData?.fileId || rowData.collectionId,
    );
    if (isRowDataInList) {
      if (defaultTrigger) {
      } else {
        handlePass(row);
      }
    } else {
      handlePass(row);
      setDefaultTrigger(false); // 更改状态
    }
  };

  // 通过接口
  async function handlePass(row: any) {
    const ids: any = [];
    const fileIdLists: any = [];
    const datasetIdList: any = [];
    const collectionIdList: any = [];
    try {
      row.forEach((item: any) => {
        ids.push(item._id);
        fileIdLists.push(item.fileId || item.collectionId);
        datasetIdList.push(item.datasetId);
        collectionIdList.push(item.collectionId);
      });

      await datasetService.knowledgeBaseApprovalStatus({
        id: ids,
        fileIdList: fileIdLists,
        reviewStatus: 'pass',
        operator: row[0].reviewStatus === 'upload_publish' ? 'upload' : 'delete',
        reason: row[0].reason,
        app_id: row[0].appId,
        datasetId: datasetIdList,
        collectionId: collectionIdList,
      });
      messageApi.success('审核通过');
      getKnowledgeBaseApprovalList();
    } catch (error) {
      messageApi.error('审核失败');
    }
  }

  /**
   * @description: 开启驳回弹窗
   * @return {*}
   */
  const handleModalOpen = (row: any) => {
    const isRowDataInList = row.items.some(
      (item: any) => item.fileId || item.collectionId === rowData?.fileId || rowData.collectionId,
    );
    setIsButtonShow(false);
    console.log(isRowDataInList, defaultTrigger);

    if (isRowDataInList) {
      if (defaultTrigger) {
      } else {
        setIsModalOpen(true);
        setRejectRow(row.items);
      }
    } else {
      setIsModalOpen(true);
      setRejectRow(row.items);
      setDefaultTrigger(false); // 更改状态
    }
  };
  /**
   * @description: 开启文档弹窗
   * @return {*}
   */
  const handleModalAllDownloadOpen = (rows: any) => {
    // const row = rows.map((item: any) => {
    //   return { ...item, checked: false };
    // });
    const deepCopy = JSON.parse(JSON.stringify(rows));

    const row = deepCopy.map((item: any) => ({
      ...item,
      checked: false,
    }));

    // console.log('New data:', row);
    setAllDownloadData(row);
    setOriginalData(row);
    modal.all.open();
    // changeAllDownload(row[0]); //默认给第一个
    setRowData(row[0]); // 默认给第一个
    setAllDownloadIndex(-1); // 默认给第一个
    setIsRepeat(false); // 重置重复状态
  };

  const changeAllDownloadIndex = (i: number, item: any) => {
    if (allDownloadIndex === i) {
      return;
    }
    setIsRepeat(false); // 把重复状态置空
    setAllDownloadIndex(i);
    changeAllDownload(item);
    setRowData(item);
    setShowTitle(false);
    setCheckoutList([]);
    setRepetitionDataList([]);
  };

  /**
   * @description: 驳回点击确定弹窗
   * @return {*}
   */
  const handleModalOk = async (row = rejectRow) => {
    const ids: any = [];
    const fileIdLists: any = [];
    const datasetIdList: any = [];
    const collectionIdList: any = [];
    try {
      row.forEach((item: any) => {
        ids.push(item._id);
        fileIdLists.push(item.fileId || item.collectionId);
        datasetIdList.push(item.datasetId);
        collectionIdList.push(item.collectionId);
      });

      await datasetService.knowledgeBaseApprovalStatus({
        id: ids,
        fileIdList: fileIdLists,
        reviewStatus: 'reject',
        operator: row[0].reviewStatus === 'upload_publish' ? 'upload' : 'delete',
        reason: rejectValue || '',
        app_id: row[0].appId,
        datasetId: datasetIdList,
        collectionId: collectionIdList,
      });
      setIsModalOpen(false);
      setIsLoadingModal(true);
      setRejectValue(''); // 把驳回原因清空
      messageApi.success('驳回成功');
      getKnowledgeBaseApprovalList();
    } catch (error) {
      messageApi.success('驳回失败');
      setIsModalOpen(false);
    }
  };

  /**
   * @description: 驳回点击取消弹窗
   * @return {*}
   */
  const handleModalCancel = () => {
    // if (!footer && allDownloadIndex > 0 && keys === '1') {
    //   modal.personnel.open();
    //   return;
    // }
    modal.all.close();
    setRejectValue(''); // 把驳回原因清空
    setDefaultValue(''); // 把输入框清空
    setDefaultTrigger(false); // 更改状态
    setRadioValue(false); // 吧后续驳回的状态清空
    setCheckoutList([]);
    setShowTitle(false);
    setRepetitionDataList([]);
  };

  // 弹框处理通过和驳回
  const handleModal = (row: any, flag: string) => {
    setIsButtonShow(true);
    if (
      row.reviewStatus === 'upload_pass' ||
      row.reviewStatus === 'delete_pass' ||
      row.reviewStatus === 'upload_reject' ||
      row.reviewStatus === 'delete_reject' ||
      row.length === 0 ||
      isRepeat
    ) {
      messageApi.error('不能重复审批');
      return;
    }
    if (flag === 'pass') {
      utilsHandle(row, flag);
      setIsShow(false);
    } else {
      setRejectValue(''); // 把驳回原因清空
      if (radioValue) {
        utilsHandle(rowData, flag);
      } else {
        setIsModalOpen(true);
      }
    }
    setDefaultTrigger(true); // 更改状态
  };
  // 更新文档状态
  const updateDownloadData = (type: string, rows: any = rejectRow) => {
    const updatedData: any = allDownloadData.map((item: any) => {
      if (
        item.checked &&
        item.reviewStatus !== 'upload_pass' &&
        item.reviewStatus !== 'upload_reject' &&
        item.reviewStatus !== 'delete_pass' &&
        item.reviewStatus !== 'delete_reject'
      ) {
        return {
          ...item,
          reviewStatus: type === 'reject' ? 'upload_reject' : 'upload_pass',
          ...(type === 'reject' && { reason: rejectValue || '已驳回' }),
        };
      }
      return item;
    });
    setAllDownloadData(updatedData);

    setOriginalData((prevOriginal) => {
      const dataMap = new Map(prevOriginal.map((item: any) => [item._id, item]));
      rows.forEach((row: any) => {
        if (dataMap.has(row._id)) {
          const current = dataMap.get(row._id)!;
          dataMap.set(row._id, {
            ...current,
            reviewStatus: type === 'reject' ? 'upload_reject' : 'upload_pass',
            ...(type === 'reject' && { reason: rejectValue || '' }),
          });
        }
      });

      return Array.from(dataMap.values());
    });
  };

  function utilsHandle(row: any, flag: string) {
    const updatedData: any = allDownloadData.map((item: any) =>
      item._id === row._id
        ? {
            ...item,
            reviewStatus: flag === 'reject' ? 'upload_reject' : 'upload_pass',
            ...(flag === 'reject' && { reason: rejectValue || '' }),
          }
        : item,
    );
    setAllDownloadData(updatedData);

    setOriginalData((prevOriginal: any) =>
      prevOriginal.map((item: any) =>
        item._id === row._id
          ? {
              ...item,
              reviewStatus: flag === 'reject' ? 'upload_reject' : 'upload_pass',
              ...(flag === 'reject' && { reason: rejectValue || '' }), // 按需更新原因
            }
          : item,
      ),
    );

    // 3. 查找下一条记录逻辑保持不变
    const currentIndex = allDownloadData.findIndex((item) => item._id === row._id);
    const isLastItem = currentIndex === allDownloadData.length - 1;

    if (!isLastItem) {
      const nextItem = allDownloadData[currentIndex + 1];
      changeAllDownload(nextItem);
      setRowData(nextItem);
      setAllDownloadIndex((pre) => pre + 1);
    } else {
      console.log('已到达最后一条数据');
      setIsRepeat(true);
    }

    // 4. 处理通过/驳回逻辑
    if (flag === 'reject') {
      handleModalOk([row]);
    } else {
      handlePass([row]);
    }
  }

  // 重写一个通过和驳回的接口（不包含批量）
  const changeHandlePassReject = (data) => {
    let pass;
    let reject;
    pass = data.filter((item) => {
      if (item.reviewStatus == 'upload_pass' || item.reviewStatus == 'delete_pass') {
        return item;
      }
    });
    reject = data.filter((item) => {
      if (item.reviewStatus == 'upload_reject' || item.reviewStatus == 'delete_reject') {
        return item;
      }
    });
    // console.log(pass, reject);
    if (pass.length != 0) {
      handlePass(pass); // 调用通过
    }
    if (reject.length != 0) {
      handleModalOk(reject); // 调用驳回
    }
    modal.all.close();
    setFooter(false); // 用完后置空
  };

  const filteredItems =
    initializeData?.is_knowledge_manager && !initializeData?.is_knowledge_reviewer
      ? items.filter((item) => item.key !== '1')
      : items;
  const filteredColumns =
    keys === '1'
      ? columns.filter((item) => item.key !== 'status')
      : columns.filter((item) => item.key !== 'items');

  return (
    <div
      style={
        {
          // padding: '12px 30px 12px 20px',
        }
      }
      className="flex h-full flex-col"
    >
      {contextHolder}
      <PagesHeader>
        知识审批
        <TipDesc title="对用户上传或关联更新到智能体知识库的文档进行审核" />
      </PagesHeader>
      <div
        className=" flex flex-1 flex-col rounded-default bg-[#FFF] px-[20px]"
        // style={{
        //   background:
        //     'linear-gradient(180deg, rgba(251, 252, 255, 0.5) 0%, rgba(255, 255, 255, 0.5) 59.81%)',
        // }}
      >
        <div
          className=""
          // style={{
          //   padding: '12px 28px 0 14px',
          // }}
        >
          <Tabs
            activeKey={keys}
            items={filteredItems}
            onChange={onChange}
            // indicator={{ align: 'center', size: 14 }}
            // className="tabs mb-0"
            // tabBarStyle={{
            //   margin: 0,
            //   border: 'none',
            // }}
          />
          <Input
            placeholder="输入应用名称/文档名称"
            onChange={(e: any) => {
              // 拿到搜索的数据
              setValue(e.target.value);
              setApprovalParam({
                page: 1,
                page_size: 10,
                offset: 0,
                searchText: e.target.value,
                // group_id: '',
                app_id: appId,
              });
            }}
            value={value}
            suffix={<SvgIcon icon="work-ic6" size={16} />}
            className="mb-[16px] !rounded-md"
            style={{
              height: '32px',
              width: '240px',
            }}
          />
        </div>
        {modal.update.isOpen ? (
          <Flex align="center" gap="middle" className="flex h-full items-center justify-center">
            <Spin size="large" />
          </Flex>
        ) : (
          <>
            {approvalData.total > 0 ? (
              <div
                className="h-full flex-1 rounded-default text-[#292D32]"
                // ref={tableRef}
              >
                <Tables<TablesProps>
                  rowClassName="bg-[#F6F7FB]"
                  columns={filteredColumns}
                  dataSource={approvalData.list}
                  pagination={false}
                  // scroll={scroll}
                  // scroll={{ x: 'calc(100vw - 400px)', y: 'calc(100vh - 306px)' }}
                  paginationProps={{
                    total: approvalData.total,
                    pageSize: approvalParam.page_size,
                    current: approvalParam.page,
                    onChange: (page, pageSize) => {
                      approvalParam.page = page;
                      approvalParam.page_size = pageSize;
                      approvalParam.offset = (page - 1) * pageSize;
                      if (keys === '1') {
                        getKnowledgeBaseApprovalList();
                      } else {
                        getKnowledgeBaseApprovalHistoryList();
                      }
                    },
                  }}
                />

                {/* <Pagination
              defaultCurrent={6}
              total={approvalData.total}
              align="end"
              className="circle-pagination !mb-5 !mr-[47px]"
            /> */}
                {/* <div className="mb-4 ml-auto mr-10 mt-auto">
              <Pagination
                defaultCurrent={1}
                total={approvalData.total}
                pageSize={approvalParam.page_size}
                current={approvalParam.page}
                showSizeChanger
                onChange={(page, pageSize) => {
                  approvalParam.page = page;
                  approvalParam.page_size = pageSize;
                  approvalParam.offset = (page - 1) * pageSize;
                  if (keys === '1') {
                    getKnowledgeBaseApprovalList();
                  } else {
                    getKnowledgeBaseApprovalHistoryList();
                  }
                }}
              />
            </div> */}
              </div>
            ) : (
              <NotData />
            )}
          </>
        )}
      </div>
      {/* 驳回原因 */}
      <RejectReasonModal
        isApproval={isApproval}
        isModalOpen={isModalOpen}
        rowData={rowData}
        defaultTrigger={defaultTrigger}
        rejectValue={rejectValue}
        approvalHistory={approvalHistory}
        setRejectValue={setRejectValue}
        reApproval={reApproval}
        setIsModalOpen={setIsModalOpen}
        handleModalOk={handleModalOk}
        utilsHandle={utilsHandle}
        updateDownloadData={updateDownloadData}
        setIsShow={setIsShow}
        isLoadingModal={isLoadingModal}
        setIsLoadingModal={setIsLoadingModal}
      />

      {/* 展示全部文档 */}
      <ViewAllModal
        allDownloadData={allDownloadData}
        isAllDownload={modal.all.isOpen}
        isAllClose={modal.all.close}
        originalData={originalData}
        keys={keys}
        rejectValue={rejectValue}
        allDownloadIndex={allDownloadIndex}
        rowData={rowData}
        url={url}
        fileName={fileName}
        loading={loading}
        defaultValue={defaultValue}
        isShow={isShow}
        setRejectValue={setRejectValue}
        setIsModalOpen={setIsModalOpen}
        setDefaultTrigger={setDefaultTrigger}
        changeAllDownload={changeAllDownload}
        setAllDownloadData={setAllDownloadData}
        handleModalCancel={handleModalCancel}
        changeAllDownloadIndex={changeAllDownloadIndex}
        handleModal={handleModal}
        setLoading={setLoading}
        setDefaultValue={setDefaultValue}
        handlePass={handlePass}
        updateDownloadData={updateDownloadData}
        setRejectRow={setRejectRow}
        setRowData={setRowData}
        setIsShow={setIsShow}
        handleModalOk={handleModalOk}
      />

      {/* 删除文件 */}
      <TipsModals
        open={modal.delete.isOpen}
        onCancel={modal.delete.close}
        onOk={() => {
          deleteDocument();
        }}
      >
        删除文件后无法恢复，确认删除？
      </TipsModals>
    </div>
  );
}

export default AppReview;
